﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace UIapp
{
    public static class Comun
    {
        public static DateTime FechaCompilacion = new DateTime(2012, 07, 28);
        public static Point frmMainLocation;
        public static Size frmMainSize;
        private static GSQ.BusinessEntities.USUARIOS _usuario;
        private static GSQ.BusinessEntities.UTILIDADES _utilidades;
        private static GSQ.BusinessEntities.SYSTEM_CONFIG _SystemConfig;

        public static GSQ.BusinessEntities.UTILIDADES utilidades
        {
            get
            {
                if (_utilidades == null)
                    _utilidades = new GSQ.BusinessLogic.UtilidadesBL().Get();
                return _utilidades;
            }
        }

        public static GSQ.BusinessEntities.USUARIOS usuario
        {
            get
            {
                return _usuario;
            }
            set
            {
                if (_usuario != value)
                    _usuario = value;
            }
        }

        public static GSQ.BusinessEntities.SYSTEM_CONFIG systemConfig
        {
            get
            {
                if (_SystemConfig == null)
                    _SystemConfig = new GSQ.BusinessLogic.SystemConfigBL().Get();
                return _SystemConfig;
            }
        }

        static Plantillas.frmLoading _loadingFRM;

        static public void ShowMessage(string s, MessageBoxIcon ico)
        {
            MessageBox.Show(s, "G.S.Q.", MessageBoxButtons.OK, ico);
        }

        public static void ShowMessage(Exception ex)
        {
            new Plantillas.frmErrorMessage(ex).ShowDialog();
        }

        public static void ShowMessage(GSQ.BusinessEntities.EntityBase value)
        {
            StringBuilder sb = new StringBuilder();
            foreach (GSQ.BusinessEntities.BrokenRule i in value.BrokenRules)
            {
                sb.AppendLine(string.Format("-> Campo {0} {1}\r", i.PropertyName, i.Message));
            }
            new Plantillas.frmErrorMessage("Hay campos que no están correctamente completados", sb.ToString()).ShowDialog();
        }

        public static void ShowLoadingFRM()
        {
            if (_loadingFRM == null)
            {
                _loadingFRM = new Plantillas.frmLoading();
            }

            _loadingFRM.Size = new Size(frmMainSize.Width - 15, frmMainSize.Height - 40);
            _loadingFRM.Location = new Point(frmMainLocation.X + 8, frmMainLocation.Y + 30);
            _loadingFRM.ShowDialog();
        }

        public static void CloseLoadingFRM()
        {
            _loadingFRM.CloseFrm();
            _loadingFRM = null;
        }

        public enum Catalogos
        { Bancos, Ciudades, Categorias, Marcas, Medidas, Monedas, Descripciones, Departamentos, Modelos, Versiones };

        public enum OperacionesCatalogos
        { Insertar, Acturalizar };

        public static void ShowInMainMessage(string msg)
        {
            if (Program.mainfrm is frmMain)
            {
                (Program.mainfrm as frmMain).ShowMessage(msg);
            }
        }

        public static void ShowMainAlert(string caption, string msg)
        {
            if (Program.mainfrm is frmMain)
            {
                (Program.mainfrm as frmMain).radDesktopAlert1.CaptionText = caption;
                //(Program.mainfrm as frmMain).radDesktopAlert1.Container.Add(new TextBox { ScrollBars= ScrollBars.Both,Text = msg , Size = new Size(500,200)});
                (Program.mainfrm as frmMain).radDesktopAlert1.ContentText = msg;
                (Program.mainfrm as frmMain).radDesktopAlert1.Show();
            }
        }

        public static void ShowEstatusNCF()
        {
            List<GSQ.BusinessEntities.NCF> lst = new GSQ.BusinessLogic.NcfBL().GetAll().Where(a => a.RNC_REQUERIDO && a.ACTIVO).Where(a => a.HASTA - a.VALUE <= 100).ToList();
            if (lst.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (GSQ.BusinessEntities.NCF r in lst)
                {
                    sb.AppendFormat("NCF: {0}-{1} solo le restan << {2:N0} >> secuencias para facturar{3}{3}", r.DESCRIPCION, r.CONDICIONES.CONDICION, r.HASTA - r.VALUE, Environment.NewLine);

                }
                sb.Append("INFORME A CONTABILIDAD PARA QUE SOLICITE A DGII");
                ShowMainAlert("ESTATUS DE SECUENCIAS DE NCF", sb.ToString());


            }
        }



        /// <summary>  
        /// Devuelve un valor Long que especifica el número de intervalos de tiempo entre dos valores Date.  
        ///  </summary> 
        ///   <param name="interval">Obligatorio. Valor de enumeración de tiempo que se desea utilizar como unidad de diferencia entre Date1 y Date2.</param>   
        /// <param name="date1">Obligatorio. Date. Primer valor de fecha u hora que se desea utilizar en el cálculo.</param>   
        /// <param name="date2">Obligatorio. Date. Segundo valor de fecha u hora que se desea utilizar en el cálculo.</param>   
        /// <returns></returns> 
        public static long DateDiff(DateInterval interval, DateTime date1, DateTime date2)
        {
            long rs = 0;
            TimeSpan diff = date2.Subtract(date1);
            switch (interval)
            {
                case DateInterval.Day:
                case DateInterval.DayOfYear:
                    rs = (long)diff.TotalDays;
                    break;
                case DateInterval.Hour:
                    rs = (long)diff.TotalHours;
                    break;
                case DateInterval.Minute:
                    rs = (long)diff.TotalMinutes;
                    break;
                case DateInterval.Month:
                    rs = (date2.Month - date1.Month) + (12 * DateDiff(DateInterval.Year, date1, date2));
                    break;
                case DateInterval.Quarter:
                    rs = (long)Math.Ceiling((double)(DateDiff(DateInterval.Month, date1, date2) / 3.0));
                    break;
                case DateInterval.Second:
                    rs = (long)diff.TotalSeconds;
                    break;
                case DateInterval.Weekday:
                case DateInterval.WeekOfYear:
                    rs = (long)(diff.TotalDays / 7);
                    break;
                case DateInterval.Year:
                    rs = date2.Year - date1.Year;
                    break;
            }
            //switch       
            return rs;
        }//DateDiff

        public enum DateInterval { Day, DayOfYear, Hour, Minute, Month, Quarter, Second, Weekday, WeekOfYear, Year }

        #region Validaciones
        public static bool ValidaCedula(string sCedula)
        {
            int iDigital = 0;
            int p = 0;
            int t = 0;
            int d = 0;
            decimal Resultado = 0;
            int i = 0;
            string sCon = null;

            sCedula = sCedula.Replace("-", "");

            sCedula = sCedula.Trim();

            if (sCedula.Length != 11)
                return false;

            if (!decimal.TryParse(sCedula, out Resultado))
                return false;


            iDigital = int.Parse(sCedula.Substring(10, 1));
            sCon = "1212121212";
            p = 0;
            t = 0;
            d = 0;

            for (i = 0; i <= 9; i++)
            {
                sCedula = sCedula.Trim();
                p = Convert.ToInt32(sCedula.Substring(i, 1)) * Convert.ToInt32(sCon.Substring(i, 1));
                if (p > 9)
                {
                    p = p - 10 + 1;
                }
                t = t + p;
            }

            d = (10 - (t % 10)) % 10;
            if (iDigital != d)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public static bool ValidaRNC(string sRNC)
        {
            int iDigital = 0;
            int p = 0;
            int t = 0;
            int d = 0;
            int r = 0;
            decimal Resultado = 0;
            int i = 0;
            string sCon = null;

            sRNC = sRNC.Replace("-", "");

            sRNC = sRNC.Trim();

            if (sRNC.Length < 9)
                return false;

            if (!decimal.TryParse(sRNC, out Resultado))
                return false;

            iDigital = int.Parse(sRNC.Substring(8, 1));

            sCon = "79865432";
            p = 0;
            t = 0;
            r = 0;
            d = 0;

            for (i = 0; i <= 7; i++)
            {
                p = Convert.ToInt32(sRNC.Substring(i, 1)) * Convert.ToInt32(sCon.Substring(i, 1));
                t = t + p;
            }

            r = t % 11;
            d = 11 - r;
            switch (r)
            {
                case 0:
                    d = 2;
                    break;
                case 1:
                    d = 1;
                    break;
            }

            if (iDigital != d)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public static bool ValidarEmail(string email)
        {
            if (email == string.Empty)
                return false;

            if (System.Text.RegularExpressions.Regex.IsMatch(email, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
                return true;
            else
                return false;
        }
        #endregion
    }
}
